package com.zhouyu.nettyclient.config;


import com.zhouyu.nettyclient.handler.ProtoClientHandler;
import com.zhouyu.proto.PeopleProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

/**
 * @Description:客户端配置
 */
@Component
@Data
@Log4j2
public class ProtoClientConfig  implements ApplicationRunner, ApplicationListener<ContextClosedEvent> {
    private int port = 8088;
    private String host = "127.0.0.1";
    private Channel socketChannel;

    public ProtoClientConfig(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public ProtoClientConfig() {
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        clientStart();
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {

    }

    public void clientStart() throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.group(eventLoopGroup);
        bootstrap.remoteAddress(host, port);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                channel.pipeline().addLast(new ProtobufDecoder(PeopleProto.People.getDefaultInstance()));
                channel.pipeline().addLast(new ProtoClientHandler());

                channel.pipeline().addFirst(new ProtobufEncoder());
                channel.pipeline().addFirst(new ProtobufVarint32LengthFieldPrepender());

            }
        });
        ChannelFuture future = bootstrap.connect(host, port).sync();
        if (future.isSuccess()) {
            socketChannel = future.channel();
            System.out.println("连接服务端成功---------");
        }
    }

}
